package com.example.webdemo.controller;

import com.example.webdemo.bean.customer;
import com.example.webdemo.service.CustomerService;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/customers")
public class CustomerController {

    private final CustomerService customerService;

    @Autowired
    public CustomerController(CustomerService customerService) {
        this.customerService = customerService;
    }

    // 创建客户
    @PostMapping
    public ResponseEntity<customer> createCustomer(@Valid @RequestBody customer customer) {
        customer createdCustomer = customerService.createCustomer(customer);
        return ResponseEntity.status(HttpStatus.CREATED)
                .body(createdCustomer);
    }

    // 更新客户
    @PutMapping("/{id}")
    public ResponseEntity<customer> updateCustomer(
            @PathVariable int id,
            @Valid @RequestBody customer customer) {
        customer updatedCustomer = customerService.updateCustomer(id, customer);
        return ResponseEntity.ok(updatedCustomer);
    }

    // 删除客户
    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteCustomer(@PathVariable int id) {
        customerService.deleteCustomer(id);
        return ResponseEntity.noContent().build();
    }

    // 获取单个客户
    @GetMapping("/{id}")
    public ResponseEntity<customer> getCustomer(@PathVariable int id) {
        customer customer = customerService.getCustomerById(id);
        return ResponseEntity.ok(customer);
    }

    // 获取所有客户
    @GetMapping("/allcustomer")
    public ResponseEntity<List<customer>> getAllCustomers() {
        List<customer> customers = customerService.getAllCustomers();
        return ResponseEntity.ok(customers);
    }

    // 搜索客户
    @GetMapping("/search")
    public ResponseEntity<List<customer>> searchCustomers(
            @RequestParam(required = false) String custName,
            @RequestParam(required = false) String custType,
            @RequestParam(required = false) String custSource) {

        List<customer> customers = customerService.searchCustomers(custName, custType, custSource);
        return ResponseEntity.ok(customers);
    }
}